package com.imchen.cms.cmscore.service;


import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.imchen.cms.constant.CMS;
import com.imchen.cms.cmscore.dao.UserMapper;
import com.imchen.cms.exception.CmsException;
import com.imchen.cms.cmscore.model.User;
import com.imchen.cms.utils.MD5Util;
import com.imchen.cms.utils.ServiceUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Base64;
import java.util.HashMap;
import java.util.List;

/**
 * @author imchen
 * @create: 2019-01-08 19:25
 **/
@Service
public class UserService implements BaseService<User> {

    private final static Logger logger = LoggerFactory.getLogger(UserService.class);

    @Autowired
    private UserMapper mapper;

    @Autowired
    private TokenService tokenService;

    @Autowired
    private LogService logService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public HashMap<String, Integer> add(User user) throws CmsException {
        String username = user.getUsername();
        String password = user.getPassword();
        String email = user.getEmail();
        if (username.isEmpty() || password.isEmpty() || email.isEmpty()) {
            throw new CmsException("", 403);
        }
        if (username.length() < 2) {
            throw new CmsException("username must greater than two characters", 403);
        }
        if (password.length() < 6) {
            throw new CmsException("password must greater than two characters", 403);
        }
        user.setPassword(MD5Util.encode(password));
        int count = mapper.insertSelective(user);
        return ServiceUtil.toAddMap(count, user.getId());
    }

    @Override
    public User findById(int id) {
        return mapper.selectByPrimaryKey(id);
    }

    @Override
    public int removeById(int id) {
        return mapper.deleteByPrimaryKey(id);
    }

    @Override
    public int deleteById(int id) {
        return 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int update(User user) {
        return mapper.updateByPrimaryKeySelective(user);
    }

    public HashMap<String, String> login(User user) throws Exception {
        HashMap<String, String> map = new HashMap<>();
        map.put("token", null);
        User dbUser = mapper.selectByUserName(user.getUsername());

        if (dbUser != null) {

            if (dbUser.getIsDelete() == CMS.DATA_IS_DELETE) {
                throw new CmsException("该用户已经禁止登录", -1);
            }

            String loginMD5 = MD5Util.encode(user.getPassword());
            if (dbUser.getPassword().equals(loginMD5)) {
                String token = tokenService.getToken(dbUser);
                byte[] arr = Base64.getEncoder().encode(token.getBytes());
                map.put("token", new String(arr));
            } else {
                map.put("error", "密码错误");
            }

        } else {
            map.put("error", "用户名错误");
        }

        return map;
    }

    public User findByName(String name) {
        return mapper.selectByUserName(name);
    }

    public int deleteByName(String username) {
        return mapper.deleteByUserName(username);
    }

    public int deleteByUserNameLogic(String username) {
        return mapper.deleteByUserNameLogic(username, 1);
    }

    public int deleteByPrimaryKeyLogic(int id) {
        return mapper.deleteByPrimaryKeyLogic(id, 1);
    }

    public List<User> findUsers() {
        return mapper.selectUsers();
    }

    public List<User> findUsers(int index, int pageSize) {
        return mapper.selectUsers(index, pageSize);
    }

    public int restoreById(int id) {
        return mapper.deleteByPrimaryKeyLogic(id, CMS.DATA_NOT_DELETE);
    }

    public PageInfo<User> findByPageHelper(int index, int pageSize) {
        PageHelper.startPage(index, pageSize);
        List<User> userList = mapper.selectAllUsers();
        return new PageInfo<>(userList);
    }
}